import React from "react";
import { Form, Input, Button, Select, Radio, message } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import { registerApi } from "../api/user";

const Register = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();

  // 从登录页面传递过来的初始值
  const { contact, password } = location.state || {};

  // 判断 contact 是手机号还是邮箱
  const isPhone = /^\d{10,11}$/.test(contact);

  // 表单提交
  const handleSubmit = async (values) => {
    try {
      if (values.role === 1) {
        message.error("无法直接注册为超级管理员");
        return;
      }

      const registerData = {
        phone: isPhone ? contact : values.phone, // 如果 contact 是手机号，直接使用；否则从输入框收集
        email: !isPhone ? contact : values.email, // 如果 contact 是邮箱，直接使用；否则从输入框收集
        password,
        username: values.username,
        real_name: values.real_name,
        gender: values.gender,
        role: values.role,
        is_active: true,
      };

      console.log("注册数据：", registerData);

      await registerApi(registerData);
      message.success("注册成功，请登录");
      navigate("/login");
    } catch (err) {
      console.log(err);

      console.log(err.response.data.errors[0].message);

      message.error(err.response.data.errors[0].message);
    }
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        backgroundColor: "#f5f5f5",
      }}
    >
      <div
        style={{
          width: "400px",
          padding: "40px",
          backgroundColor: "#fff",
          borderRadius: "8px",
          boxShadow: "0 4px 10px rgba(0, 0, 0, 0.1)",
        }}
      >
        <h2 style={{ textAlign: "center", marginBottom: "20px" }}>
          完善注册信息
        </h2>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ contact }}
        >
          {/* 用户名 */}
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          {/* 真实姓名 */}
          <Form.Item
            label="真实姓名"
            name="real_name"
            rules={[{ required: true, message: "请输入真实姓名" }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>

          {/* 手机号（如果 contact 是邮箱，需要额外收集手机号） */}
          {!isPhone && (
            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^\d{10,11}$/, message: "手机号格式不正确" },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
          )}

          {/* 邮箱（如果 contact 是手机号，需要额外收集邮箱） */}
          {isPhone && (
            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "邮箱格式不正确" },
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          )}

          {/* 性别 */}
          <Form.Item
            label="性别"
            name="gender"
            rules={[{ required: true, message: "请选择性别" }]}
          >
            <Radio.Group>
              <Radio value="男">男</Radio>
              <Radio value="女">女</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 用户类型 */}
          <Form.Item
            label="用户类型"
            name="role"
            rules={[{ required: true, message: "请选择用户类型" }]}
          >
            <Select placeholder="请选择用户类型">
              <Select.Option value={2}>招聘方</Select.Option>
              <Select.Option value={3}>求职者</Select.Option>
            </Select>
          </Form.Item>

          {/* 提交按钮 */}
          <Button
            type="primary"
            htmlType="submit"
            style={{ width: "100%", marginTop: "20px" }}
          >
            完成注册
          </Button>
        </Form>
      </div>
    </div>
  );
};

export default Register;
